package cn.bone.kafka.kafka09;

import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.*;

public class CustomConsumerSeekTime {

    public static void main(String[] args) {

        // 0、配置
        Properties properties = new Properties();
        // 连接集群 bootstrap.servers
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.1.5:3001,192.168.1.5:3002,192.168.1.5:3003");
        // 反序列化
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());

        // 配置消费者组id 名字可以随便取
        // 测试指定offset消费，每次执行完，需要修改消费者名称
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "sui_bian");

        // 1、创建一个消费者
        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(properties);

        // 2、订阅主题
        ArrayList<String> topics = new ArrayList<>();
        topics.add("first");
        kafkaConsumer.subscribe(topics);

        // 获取分区信息
        Set<TopicPartition> assignment = kafkaConsumer.assignment();

        // 保证分区分配方案已经指定完毕
        while(assignment.size() == 0){
            // 拉取一次数据
            kafkaConsumer.poll(Duration.ofSeconds(1));
            // 更新获取的分区信息
            assignment = kafkaConsumer.assignment();
        }

        // 希望把时间转换成对应的offset
        Map<TopicPartition, Long> topicPartitionLongMap = new HashMap<>();
        // 封装对应的集合
        for(TopicPartition topicPartition : assignment){
            // 获取当前时间前一天的数据
            long targetTime = System.currentTimeMillis() - 1 * 24 * 3600 * 1000;
            topicPartitionLongMap.put(topicPartition, targetTime);
        }

        Map<TopicPartition, OffsetAndTimestamp> topicPartitionOffsetAndTimestampMap =
                kafkaConsumer.offsetsForTimes(topicPartitionLongMap);

        // 指定位置进行消费,通过时间转换获取到
        for(TopicPartition partition : assignment){
            OffsetAndTimestamp offsetAndTimestamp = topicPartitionOffsetAndTimestampMap.get(partition);
            kafkaConsumer.seek(partition, offsetAndTimestamp.offset());
        }

        // 3、消费数据
        while (true){
            // 每秒拉取一次数据
            ConsumerRecords<String, String> consumerRecords = kafkaConsumer.poll(Duration.ofSeconds(1));
            for(ConsumerRecord<String, String> consumerRecord : consumerRecords){
                System.out.println(consumerRecord);
            }
        }
    }
}
